package com.tanhua.autoconfig.template;

import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.tanhua.autoconfig.properties.OssProperties;

import java.io.InputStream;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.UUID;

/**
 * 人脸识别
 * @author lk
 * @date 2022-03-24
 */
public class OssTemplate {

    private OssProperties ossProperties;

    public OssTemplate(OssProperties ossProperties) {
        this.ossProperties = ossProperties;
    }

    public String upload(String filename, InputStream is) {
        //拼写图片路径
        filename = new SimpleDateFormat("yyyy/MM/dd").format(new Date())//格式化日期
                + "/" + UUID.randomUUID().toString()  //使用uu设置全球唯一id
                + filename.substring(filename.lastIndexOf(".")); //将后缀截取出来

        //填写Bucket所在地域对应的Endpoint
        String endpoint = ossProperties.getEndpoint();
        String accessKeyId = ossProperties.getAccessKey();
        String accessKeySecret = ossProperties.getSecret();

        // 创建OSSClient实例
        OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId,accessKeySecret);

        // 填写Byte数组。
        // 填写Bucket名称和Object完整路径。Object完整路径中不能包含Bucket名称
        ossClient.putObject(ossProperties.getBucketName(),filename,is);


        String url = ossProperties.getUrl()+"/"+filename;
        //关闭OSSClient
        ossClient.shutdown();
        return url;
    }
}
